#include "papers.h"
#include "helper.h"
#include "transfer.h"


struct papers_t global_papers;

struct papers_t * get_papers()
{
  static struct papers_t * papers = 0;
  if (papers == 0) {
    papers = &global_papers;
    papers_create(papers);
  }
  return papers;
}

paper_id_t * paper_add_1_svc(paper_info_t * info, struct svc_req * req)
{
  static int result = 0;
  result = papers_add(get_papers(), info->author, info->title, info->file_name);
  return &result;
}

paper_info_t * get_paper_1_svc(paper_id_t * paper_id, struct svc_req * req)
{
  static struct paper_info_t result;
  struct paper_t * paper = get_paper_by_id(get_papers(), *paper_id);
  if (paper == 0)
    paper_info_error_create(&result, "Not such paper id");
  else {
    paper_info_create(&result, paper->author, paper->title, paper->file_name);  
    result.next_paper_id = (*paper_id >= papers_get_last_id(get_papers())) ? -1 : (*paper_id) + 1;
  }
  return &result;
}

block_t * get_block_1_svc(block_request_t * request, struct svc_req * req)
{
  static block_t result;
  struct paper_t * paper;
  paper = get_paper_by_id(get_papers(), request->paper_id);
  if (paper == 0) {
    create_error_block(&result, "Not such paper id");
    return &result;
  }
  char buffer[BLOCK_SIZE];
  int size = paper_get_block(paper, request->block_id, buffer);
  create_block(&result, request->block_id, buffer, size);
  return &result;
}

error_info_t * add_block_1_svc(block_t * block, struct svc_req * req) 
{
  struct paper_t * paper;
  static error_info_t result;
  paper = get_paper_by_id(get_papers(), block->paper_id);
  if (paper == 0) {
    create_error(&result, "Not such paper id");
    return &result;
  }
  paper_add_block(paper, block->data, block->size);
  create_no_error(&result);
  return &result;
}


